﻿using AutoMan.Dtos;
using AutoMan.Models;
using AutoMan.Helper;
using SqlSugar;

namespace AutoMan.Handles
{
    public class EntityHandle:IDisposable
    {
        readonly SqlSugar.SqlSugarScope db;
        private string tableName;
        private bool disposed;
        public EntityHandle(string TableName)
        {
            db = SqlsugarHelper.Db;
            tableName = TableName;
        }
        /// <summary>
        /// 通过实现IDisposable接口释放资源
        /// </summary>
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }
        /// <summary>
        /// 释放资源实现
        /// </summary>
        /// <param name="disposing"></param>
        protected virtual void Dispose(bool disposing)
        {
            if (!disposed)
            {
                if (disposing)
                {
                    // Release managed resources
                    if (db != null)
                    this.db.Dispose();
                }
                // Release unmanaged resources（释放非托管资源）
                disposed = true;
            }
        }

        public void InitDataTable(int formId)
        {
            var formInfo=db.Queryable<FormModel>().First(it => it.编号 == formId);
            var formFields = db.Queryable<FormFieldModel>().Where(it => it.表单编号 == formInfo.编号).ToList();
            var typeBilder = db.DynamicBuilder().CreateClass(formInfo.别名, new SugarTable() { });

            foreach (var formField in formFields)
            {
                if (formField.名称 == "编号")
                {
                    typeBilder.CreateProperty(formField.名称, typeof(int), new SugarColumn() { IsPrimaryKey = true, IsIdentity = true });
                    continue;
                }
                typeBilder.CreateProperty(formField.名称, typeof(string), new SugarColumn() { });
            }
            
            var type = typeBilder.BuilderType();
            db.CodeFirst.InitTables(type);
        }
        public dynamic Info(int id)
        {
            return db.Queryable<dynamic>().AS(tableName).Where("编号=@id",new { Id = id }).First();
        }
        public List<dynamic> List(QueryDto queryDto)
        {
            if (queryDto == null)
            {
                return db.Queryable<dynamic>().AS(tableName).ToList();
            }
            return db.Queryable<dynamic>().AS(tableName).Where(queryDto.WhereString, queryDto.Parameters).ToList();
        }
        public List<TreeListDto> TreeList()
        {
            var dynamics=db.Queryable<dynamic>().AS(tableName).ToList();
            var list = MapDynamicListToType(dynamics);
            return list;
        }
        public void Add(Dictionary<string, object> keyValues)
        {
            db.Insertable(keyValues).AS(tableName).ExecuteCommand();
        }

        public void Delete(int Id)
        {
            db.Deleteable<object>().AS(tableName).Where("编号=@Id", new { Id}).ExecuteCommand();
        }
        public void Delete(int[] ids)
        {
            db.Deleteable<object>().AS(tableName).Where("编号 in (@Ids) ", new { Ids = ids }).ExecuteCommand();
        }

        public void Update(Dictionary<string, object> keyValues)
        {
            db.Updateable(keyValues).AS(tableName).WhereColumns("编号").ExecuteCommand();
        }
        public static List<TreeListDto> MapDynamicListToType(List<dynamic> dynamicList)
        {
            var list = new List<TreeListDto>();
            foreach (dynamic dynamic in dynamicList)
            {
                var Id=int.Parse(Convert.ToString(dynamic.编号));
                var Name=Convert.ToString(dynamic.名称);
                var ParentId = 0;
                try
                {
                    ParentId = int.Parse(Convert.ToString(dynamic?.父级编号));
                }
                catch (Exception)
                {
                    
                }
                var treeListDto = new TreeListDto
                {
                    编号 = Id,
                    名称 = Name,
                    父级编号 = ParentId
                };
                list.Add(treeListDto);
            }
            return list;
        }
    }
}
